





from sklearn.svm import SVC
from sklearn.feature_selection import RFECV
import pandas as pd
import numpy as np





# 分别从 train.csv 和 test.csv中读取出训练集和测试集
train_data = pd.read_csv('../../RefreshedData/refreshed_train.csv')
test_data = pd.read_csv('../../RefreshedData/refreshed_test.csv')
X_train = train_data.iloc[:, :-1].values
y_train = train_data.iloc[:, -1].values


# 构建 Svm 分类器
clf = SVC(kernel='linear', C=1)
rfecv = RFECV(estimator=clf, step=1, cv=5, verbose=2)


rfecv.fit(X_train, y_train)


# 得出 frame 各属性的 bool 索引
support_train_index = list(rfecv.support_) + [True]
support_test_index = list(rfecv.support_)
print(rfecv.support_)


# 选择 bool 索引中为 True 的属性，反之丢弃
train_selected = train_data.loc[:, support_train_index]
test_selected = test_data.loc[:, support_test_index]


# 将选择的数据集保存
train_selected.to_csv('../../FeatureSelectedData/Svm/svm_train.csv', index=False)
test_selected.to_csv('../../FeatureSelectedData/Svm/svm_test.csv', index=False)








from joblib import dump, load





final_train_data = pd.read_csv('../../FeatureSelectedData/Svm/svm_train.csv')
final_X_train = final_train_data.iloc[:, :-1]
final_y_train = final_train_data.iloc[:, -1]

clf.fit(final_X_train, final_y_train)

dump(clf, '../../ModelFile/Svm/svm_model.joblib')
print("Model saved as svm_model.joblib")





def Svm(test_data):
    clf = load('../../ModelFile/Svm/svm_model.joblib')
    y_predicted = clf.predict(test_data)
    return y_predicted





final_test_data = pd.read_csv('../../FeatureSelectedData/Svm/svm_test.csv')
result_file = pd.read_csv('../../RawData/sample_submission.csv')
predictions = Svm(final_test_data)
result_file["Transported"] = pd.Series(predictions, result_file.index)
result_file.to_csv('../../predictions/Svm/result_svm.csv', index=False)



